<template>
  <div class="page-container router-view-container">
    <!-- 页面头部 -->
    <PageHeader title="房源管理" :subtitle="`总数: ${state.totalItems}`">
      <!-- 搜索和筛选区域 -->
      <template #search-filters>
        <div class="house-search">
          <span class="label">门牌地址：</span>
          <el-input
            v-model="searchKeyword"
            placeholder="请输入门牌地址搜索"
            style="width: 300px"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="house-function-select">
          <span class="label">房屋功能：</span>
          <el-select
            v-model="searchParams.fwgn"
            placeholder="房屋功能"
            clearable
            style="width: 150px"
            @change="handleFilterChange"
          >
            <el-option label="全部" value="" />
            <el-option label="办公" value="办公" />
            <el-option label="住宅" value="住宅" />
            <el-option label="商业" value="商业" />
            <el-option label="工业" value="工业" />
            <el-option label="其他" value="其他" />
          </el-select>
        </div>
        
        <div class="house-status-select">
          <span class="label">状态：</span>
          <el-select
            v-model="searchParams.zt"
            placeholder="状态"
            clearable
            style="width: 150px"
            @change="handleFilterChange"
          >
            <el-option label="全部" value="" />
            <el-option label="自用" :value="1" />
            <el-option label="待租" :value="2" />
            <el-option label="已租" :value="3" />
            <el-option label="待售" :value="4" />
            <el-option label="已售" :value="5" />
          </el-select>
        </div>
        
        <div class="house-operator-select">
          <span class="label">经营方：</span>
          <el-input
            v-model="searchParams.jyf"
            placeholder="请输入经营方"
            style="width: 200px"
            clearable
            @input="handleFilterChange"
          >
            <template #prefix>
              <el-icon><OfficeBuilding /></el-icon>
            </template>
          </el-input>
        </div>
      </template>

      <!-- 主要操作按钮 -->
      <template #main-actions>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新建房源
        </el-button>
        
        <el-upload
          ref="uploadRef"
          :show-file-list="false"
          :before-upload="handleImport"
          accept=".xlsx,.xls"
        >
          <el-button type="warning">
            <el-icon><Upload /></el-icon>
            导入
          </el-button>
        </el-upload>
        
        <el-button type="success" @click="handleExportCommand('export')">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
        
        <el-dropdown @command="handleMoreAction">
          <el-button type="info">
            <el-icon><More /></el-icon>
            更多
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="template">
                <el-icon><DocumentCopy /></el-icon>
                下载模板
              </el-dropdown-item>
              <el-dropdown-item command="reset" icon="Refresh">重置筛选</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        
        <el-tooltip
          content="点击查看导入说明"
          placement="top"
        >
          <el-icon class="help-icon" @click="showImportHelp = true"><QuestionFilled /></el-icon>
        </el-tooltip>
      </template>

      <!-- 更多操作下拉菜单 -->
      <template #more-actions>
        <!-- 空内容，所有按钮已移到main-actions -->
      </template>
    </PageHeader>

    <!-- 数据表格 -->
    <div class="table-container">
        <BaseTable
          table-name="house-table"
          :columns="tableColumns"
          :data="state.pageData"
          :loading="state.loading"
          :sort="sort"
          @sort-change="handleSortChange"
        >
          <!-- 门牌地址 -->
          <template #mpdz="{ row }">
            <span class="address-text">{{ row.mpdz }}</span>
          </template>
          
          <!-- 房号 -->
          <template #fh="{ row }">
            <span class="room-number">{{ row.fh }}</span>
          </template>
          
          <!-- 房屋功能 -->
          <template #fwgn="{ row }">
            <el-tag
              :type="getFunctionTagType(row.fwgn)"
              size="small"
            >
              {{ row.fwgn }}
            </el-tag>
          </template>
          
          <!-- 建筑面积 -->
          <template #jzmj="{ row }">
            <span class="area-text">{{ row.jzmj }}㎡</span>
          </template>
          
          <!-- 套内面积 -->
          <template #tnmj="{ row }">
            <span class="area-text">{{ row.tnmj }}㎡</span>
          </template>
          
          <!-- 公摊面积 -->
          <template #gtmj="{ row }">
            <span class="area-text">{{ row.gtmj }}㎡</span>
          </template>
          
          <!-- 状态 -->
          <template #zt="{ row }">
            <el-tag
              :type="getStatusTagType(row.zt)"
              size="small"
            >
              {{ getStatusText(row.zt) }}
            </el-tag>
          </template>
          
          <!-- 经营方 -->
          <template #jyf="{ row }">
            <span class="jyf-text">{{ row.jyf }}</span>
          </template>
          
          <!-- 创建日期 -->
          <template #cjrq="{ row }">
            <span class="date-text">{{ formatDate(row.cjrq) }}</span>
          </template>
          
          <!-- 操作 -->
          <template #actions="{ row }">
            <div class="action-buttons">
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </BaseTable>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="state.currentPage"
          v-model:page-size="state.pageSize"
          :total="state.totalItems"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      class="management-dialog"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="dialog-form"
      >
        <el-form-item label="门牌地址" prop="mpdz">
          <el-input
            v-model="formData.mpdz"
            placeholder="请输入门牌地址"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="房号" prop="fh">
          <el-input
            v-model="formData.fh"
            placeholder="请输入房号"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="房屋功能" prop="fwgn">
          <el-select
            v-model="formData.fwgn"
            placeholder="请选择房屋功能"
            style="width: 100%"
          >
            <el-option label="办公" value="办公" />
            <el-option label="住宅" value="住宅" />
            <el-option label="商业" value="商业" />
            <el-option label="车位" value="车位" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="建筑面积" prop="jzmj">
          <el-input-number
            v-model="formData.jzmj"
            :min="0"
            :precision="2"
            :step="0.01"
            style="width: 100%"
            placeholder="请输入建筑面积"
          />
        </el-form-item>
        
        <el-form-item label="套内面积" prop="tnmj">
          <el-input-number
            v-model="formData.tnmj"
            :min="0"
            :precision="2"
            :step="0.01"
            style="width: 100%"
            placeholder="请输入套内面积"
          />
        </el-form-item>
        
        <el-form-item label="公摊面积" prop="gtmj">
          <el-input-number
            v-model="formData.gtmj"
            :min="0"
            :precision="2"
            :step="0.01"
            style="width: 100%"
            placeholder="请输入公摊面积"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="zt">
          <el-select
            v-model="formData.zt"
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-option label="自用" :value="1" />
            <el-option label="待租" :value="2" />
            <el-option label="已租" :value="3" />
            <el-option label="待售" :value="4" />
            <el-option label="已售" :value="5" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="经营方" prop="jyf">
          <el-input
            v-model="formData.jyf"
            placeholder="请输入经营方"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 导入说明对话框 -->
    <el-dialog
      v-model="showImportHelp"
      title="导入说明"
      width="600px"
      class="help-dialog"
    >
      <div class="import-help-content">
        <h4>📋 导入格式说明</h4>
        <p>请按照以下格式填写Excel文件：</p>
        
        <div class="format-table">
          <table>
            <thead>
              <tr>
                <th>列名</th>
                <th>字段名</th>
                <th>类型</th>
                <th>必填</th>
                <th>说明</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>门牌地址</td>
                <td>mpdz</td>
                <td>文本</td>
                <td>是</td>
                <td>房屋门牌地址，最大200字符</td>
              </tr>
              <tr>
                <td>房号</td>
                <td>fh</td>
                <td>文本</td>
                <td>是</td>
                <td>房屋编号，最大20字符</td>
              </tr>
              <tr>
                <td>房屋功能</td>
                <td>fwgn</td>
                <td>文本</td>
                <td>否</td>
                <td>办公/住宅/商业/工业/其他，默认"办公"</td>
              </tr>
              <tr>
                <td>建筑面积</td>
                <td>jzmj</td>
                <td>数字</td>
                <td>是</td>
                <td>单位：平方米，必须大于0</td>
              </tr>
              <tr>
                <td>套内面积</td>
                <td>tnmj</td>
                <td>数字</td>
                <td>是</td>
                <td>单位：平方米，必须大于0</td>
              </tr>
              <tr>
                <td>公摊面积</td>
                <td>gtmj</td>
                <td>数字</td>
                <td>是</td>
                <td>单位：平方米，不能为负数</td>
              </tr>
              <tr>
                <td>状态</td>
                <td>zt</td>
                <td>数字</td>
                <td>否</td>
                <td>1-自用，2-待租，3-已租，4-待售，5-已售，默认1</td>
              </tr>
              <tr>
                <td>经营方</td>
                <td>jyf</td>
                <td>文本</td>
                <td>否</td>
                <td>经营方名称，最大100字符</td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <div class="import-tips">
          <h4>💡 导入提示</h4>
          <ul>
            <li>支持 .xlsx 和 .xls 格式的Excel文件</li>
            <li>文件大小不能超过10MB</li>
            <li>建筑面积必须等于套内面积加公摊面积</li>
            <li>门牌地址必须唯一，不能重复</li>
            <li>经营方为可选字段，最大100字符</li>
            <li>建议先下载模板，按照模板格式填写数据</li>
            <li>每1000条数据会批量保存一次</li>
            <li><strong>注意：如果下载的模板中没有经营方列，请手动添加一列"经营方"</strong></li>
            <li><strong>或者点击"备用模板"按钮下载包含经营方列的CSV模板</strong></li>
          </ul>
        </div>
        
        <div class="import-example">
          <h4>📝 示例数据</h4>
          <div class="example-table">
            <table>
              <thead>
                <tr>
                  <th>门牌地址</th>
                  <th>房号</th>
                  <th>房屋功能</th>
                  <th>建筑面积</th>
                  <th>套内面积</th>
                  <th>公摊面积</th>
                  <th>状态</th>
                  <th>经营方</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>北京市朝阳区建国路88号</td>
                  <td>A座101</td>
                  <td>办公</td>
                  <td>120.50</td>
                  <td>100.00</td>
                  <td>20.50</td>
                  <td>1</td>
                  <td>某公司</td>
                </tr>
                <tr>
                  <td>北京市海淀区中关村大街1号</td>
                  <td>B座202</td>
                  <td>住宅</td>
                  <td>150.00</td>
                  <td>125.00</td>
                  <td>25.00</td>
                  <td>2</td>
                  <td>另一公司</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showImportHelp = false">关闭</el-button>
          <el-button type="primary" @click="handleDownloadTemplate">下载模板</el-button>
          <el-button type="warning" @click="generateFrontendTemplate">备用模板</el-button>
        </div>
      </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Download, Upload, ArrowDown, Refresh, Document, DocumentCopy, QuestionFilled, OfficeBuilding, More } from '@element-plus/icons-vue'
import BaseTable from '@/components/tools/BaseTable.vue'
import useTable from '@/composables/useTable.js'
import houseApi from '@/api/houseApi.js'
import { formatDate } from '@/utils/formatter.js'
import PageHeader from '@/components/layout/PageHeader.vue'

// 使用通用表格组合式API
const { state, loadData, handleSortChange, updateSearchParams, resetSearchParams, setSearchKeyword, handleSizeChange, handleCurrentChange } = useTable(houseApi.getList)

// 搜索关键词
const searchKeyword = ref('')

// 搜索参数
const searchParams = reactive({
  mpdz: '',
  fwgn: '',
  zt: '',
  jyf: '' // 新增经营方搜索参数
})

// 排序
const sort = ref({})

// 表格列配置
const tableColumns = [
  { prop: 'mpdz', label: '门牌地址', minWidth: 200, slot: 'mpdz', visible: true },
  { prop: 'fh', label: '房号', width: 140, slot: 'fh', visible: true },
  { prop: 'fwgn', label: '房屋功能', width: 140, slot: 'fwgn', visible: true },
  { prop: 'jzmj', label: '建筑面积', width: 140, slot: 'jzmj', visible: true },
  { prop: 'tnmj', label: '套内面积', width: 140, slot: 'tnmj', visible: true },
  { prop: 'gtmj', label: '公摊面积', width: 140, slot: 'gtmj', visible: true },
  { prop: 'zt', label: '状态', width: 120, slot: 'zt', visible: true },
  { prop: 'jyf', label: '经营方', width: 150, slot: 'jyf', visible: true },
  { prop: 'cjrq', label: '创建日期', width: 140, slot: 'cjrq', visible: true },
  { prop: 'actions', label: '操作', width: 250, slot: 'actions', fixed: 'right', visible: true }
]

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const showImportHelp = ref(false)
const formData = reactive({
  id: null,
  mpdz: '',
  fh: '',
  fwgn: '办公',
  jzmj: 0,
  tnmj: 0,
  gtmj: 0,
  zt: 1,  // 默认自用状态
  jyf: '' // 新增经营方字段
})

// 表单验证规则
const formRules = {
  mpdz: [
    { required: true, message: '请输入门牌地址', trigger: 'blur' },
    { max: 200, message: '门牌地址不能超过200个字符', trigger: 'blur' }
  ],
  fh: [
    { required: true, message: '请输入房号', trigger: 'blur' },
    { max: 20, message: '房号不能超过20个字符', trigger: 'blur' }
  ],
  fwgn: [
    { required: true, message: '请选择房屋功能', trigger: 'change' }
  ],
  jzmj: [
    { required: true, message: '请输入建筑面积', trigger: 'blur' },
    { type: 'number', min: 0, message: '建筑面积必须大于0', trigger: 'blur' }
  ],
  tnmj: [
    { required: true, message: '请输入套内面积', trigger: 'blur' },
    { type: 'number', min: 0, message: '套内面积必须大于0', trigger: 'blur' }
  ],
  gtmj: [
    { required: true, message: '请输入公摊面积', trigger: 'blur' },
    { type: 'number', min: 0, message: '公摊面积不能为负数', trigger: 'blur' }
  ],
  zt: [
    { required: true, message: '请选择状态', trigger: 'change' },
    { type: 'number', min: 1, max: 5, message: '状态值必须在1-5之间', trigger: 'change' }
  ],
  jyf: [
    { max: 100, message: '经营方不能超过100个字符', trigger: 'blur' }
  ]
}

// 搜索处理
const handleSearch = () => {
  updateSearchParams({ mpdz: searchKeyword.value })
  loadData()
}

// 筛选处理
const handleFilterChange = () => {
  updateSearchParams(searchParams)
  loadData()
}

// 重置处理
const handleReset = () => {
  searchKeyword.value = ''
  Object.keys(searchParams).forEach(key => {
    searchParams[key] = ''
  })
  resetSearchParams()
  loadData()
}

// 更多操作处理
const handleMoreAction = (command) => {
  switch (command) {
    case 'export':
      handleExportCommand('export')
      break
    case 'template':
      handleExportCommand('template')
      break
    case 'reset':
      handleReset()
      break
    default:
      break
  }
}

// 新增处理
const handleAdd = () => {
  dialogTitle.value = '新增房源'
  resetForm()
  dialogVisible.value = true
}

// 编辑处理
const handleEdit = (row) => {
  dialogTitle.value = '编辑房源'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除处理
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除房源 "${row.mpdz} - ${row.fh}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await houseApi.delete(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交处理
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    // 验证面积关系
    if (formData.jzmj !== formData.tnmj + formData.gtmj) {
      ElMessage.error('建筑面积必须等于套内面积加公摊面积')
      return
    }
    
    if (formData.id) {
      // 更新
      await houseApi.update(formData.id, formData)
      ElMessage.success('更新成功')
    } else {
      // 新增
      await houseApi.create(formData)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 对话框关闭处理
const handleDialogClose = () => {
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    mpdz: '',
    fh: '',
    fwgn: '办公',
    jzmj: 0,
    tnmj: 0,
    gtmj: 0,
    zt: 1,  // 默认自用状态
    jyf: '' // 新增经营方字段
  })
  formRef.value?.clearValidate()
}

// 导出处理
const handleExportCommand = async (command) => {
  try {
    if (command === 'export') {
      ElMessage.info('正在导出数据，请稍候...')
      const response = await houseApi.exportExcel({
        mpdz: searchParams.mpdz,
        fwgn: searchParams.fwgn,
        zt: searchParams.zt,
        jyf: searchParams.jyf // 导出时也包含经营方筛选
      })
      downloadFile(response, `房源信息_${new Date().toISOString().split('T')[0]}.xlsx`)
      ElMessage.success('导出成功')
    } else if (command === 'template') {
      ElMessage.info('正在下载模板，请稍候...')
      const response = await houseApi.exportTemplate()
      downloadFile(response, '房源信息导入模板.xlsx')
      ElMessage.success('模板下载成功，请按照模板格式填写数据')
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error(`导出失败: ${error.message || '未知错误'}`)
  }
}

// 导入处理
const handleImport = async (file) => {
  try {
    // 验证文件类型
    const allowedTypes = [
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
      'application/vnd.ms-excel' // .xls
    ]
    
    if (!allowedTypes.includes(file.type)) {
      ElMessage.error('请选择正确的Excel文件格式（.xlsx 或 .xls）')
      return false
    }
    
    // 验证文件大小（限制为10MB）
    const maxSize = 10 * 1024 * 1024 // 10MB
    if (file.size > maxSize) {
      ElMessage.error('文件大小不能超过10MB')
      return false
    }
    
    ElMessage.info('正在导入数据，请稍候...')
    await houseApi.importExcel(file)
    ElMessage.success('导入成功')
    loadData()
    return false // 阻止自动上传
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error(`导入失败: ${error.message || '未知错误'}`)
    return false
  }
}

// 下载文件
const downloadFile = (response, filename) => {
  console.log('downloadFile 参数:', { response, filename })
  console.log('response 类型:', typeof response)
  console.log('response 结构:', response)
  
  let blob = null
  
  // 处理不同的响应格式
  if (response instanceof Blob) {
    blob = response
  } else if (response && response.data instanceof Blob) {
    blob = response.data
  } else if (response && response.data) {
    // 尝试将数据转换为blob
    try {
      blob = new Blob([response.data])
    } catch (error) {
      console.error('无法将响应数据转换为Blob:', error)
    }
  }
  
  console.log('blob 类型:', typeof blob)
  console.log('blob 是否为Blob实例:', blob instanceof Blob)
  
  if (!(blob instanceof Blob)) {
    console.error('下载失败：响应不是Blob格式', blob)
    console.error('响应详情:', {
      responseType: typeof response,
      responseKeys: response ? Object.keys(response) : 'null',
      dataType: typeof response?.data,
      dataKeys: response?.data ? Object.keys(response.data) : 'null'
    })
    ElMessage.error('下载失败：文件格式错误')
    return
  }
  
  try {
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    console.log('文件下载成功:', filename)
  } catch (error) {
    console.error('创建下载链接失败:', error)
    ElMessage.error('下载失败：创建下载链接失败')
  }
}

// 获取状态文本
const getStatusText = (zt) => {
  const statusMap = {
    1: '自用',
    2: '待租',
    3: '已租',
    4: '待售',
    5: '已售'
  }
  return statusMap[zt] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (zt) => {
  const typeMap = {
    1: 'success',   // 自用 - 绿色
    2: 'warning',   // 待租 - 橙色
    3: 'info',      // 已租 - 蓝色
    4: 'warning',   // 待售 - 橙色
    5: 'danger'     // 已售 - 红色
  }
  return typeMap[zt] || 'default'
}

// 获取功能标签类型
const getFunctionTagType = (fwgn) => {
  const typeMap = {
    '办公': 'primary',
    '住宅': 'success',
    '商业': 'warning',
    '工业': 'info',
    '其他': 'default'
  }
  return typeMap[fwgn] || 'default'
}

// 下载模板
const handleDownloadTemplate = async () => {
  try {
    ElMessage.info('正在下载模板，请稍候...')
    const response = await houseApi.exportTemplate()
    console.log('模板下载响应:', response)
    console.log('响应类型:', typeof response)
    console.log('响应数据结构:', {
      hasData: !!response.data,
      dataType: typeof response.data,
      isBlob: response.data instanceof Blob,
      responseKeys: Object.keys(response)
    })
    
    // 尝试下载
    downloadFile(response, '房源信息导入模板.xlsx')
    ElMessage.success('模板下载成功，请按照模板格式填写数据')
    
    // 添加提示说明
    setTimeout(() => {
      ElMessage({
        message: '注意：如果模板中没有经营方列，请手动添加一列"经营方"',
        type: 'warning',
        duration: 5000
      })
    }, 1000)
  } catch (error) {
    console.error('下载模板失败:', error)
    
    // 如果是网络错误，提供更详细的错误信息
    if (error.response) {
      console.error('错误响应:', error.response)
      ElMessage.error(`下载模板失败: ${error.response.status} - ${error.response.statusText}`)
    } else if (error.request) {
      console.error('请求错误:', error.request)
      ElMessage.error('下载模板失败: 网络请求失败，请检查网络连接')
    } else {
      ElMessage.error(`下载模板失败: ${error.message || '未知错误'}`)
    }
  }
}

// 生成前端模板（备用方案）
const generateFrontendTemplate = () => {
  try {
    // 创建CSV格式的模板数据
    const headers = ['门牌地址', '房号', '房屋功能', '建筑面积', '套内面积', '公摊面积', '状态', '经营方']
    const exampleData = [
      ['北京市朝阳区建国路88号', 'A座101', '办公', '120.50', '100.00', '20.50', '1', '某公司'],
      ['北京市海淀区中关村大街1号', 'B座202', '住宅', '150.00', '125.00', '25.00', '2', '另一公司']
    ]
    
    // 组合数据
    const csvContent = [
      headers.join(','),
      ...exampleData.map(row => row.join(','))
    ].join('\n')
    
    // 添加BOM以确保Excel正确识别中文
    const BOM = '\uFEFF'
    const blob = new Blob([BOM + csvContent], { 
      type: 'text/csv;charset=utf-8;' 
    })
    
    // 下载文件
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '房源信息导入模板_包含经营方.csv'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('前端模板生成成功，包含经营方列')
  } catch (error) {
    console.error('生成前端模板失败:', error)
    ElMessage.error('生成前端模板失败')
  }
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style scoped>
@import '@/styles/page.css';

/* 搜索筛选样式 */
.house-search,
.house-function-select,
.house-status-select,
.house-operator-select {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* Header按钮样式 */
:deep(.page-header-component .main-actions) {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.page-header-component .main-actions .el-button) {
  margin: 0;
}

:deep(.page-header-component .main-actions .el-upload) {
  margin: 0;
}

:deep(.page-header-component .main-actions .el-upload .el-button) {
  margin: 0;
}

/* 响应式设计 - Header按钮 */
@media (max-width: 768px) {
  :deep(.page-header-component .main-actions) {
    gap: 6px;
  }
}

@media (max-width: 480px) {
  :deep(.page-header-component .main-actions) {
    justify-content: center;
    flex-wrap: wrap;
    gap: 8px;
  }
}

.label {
  font-size: 14px;
  color: var(--text-secondary, #606266);
  white-space: nowrap;
}

.help-icon {
  font-size: 18px;
  color: var(--text-secondary, #606266);
  cursor: pointer;
  margin-left: 0;
  padding: 8px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.help-icon:hover {
  color: var(--primary-color, #409eff);
  background-color: rgba(64, 158, 255, 0.1);
}

/* 表格内容字体样式 - 与合同管理页面保持一致 */
.address-text {
  font-weight: normal;
  color: #303133;
}

.room-number {
  font-weight: normal;
  color: #303133;
}

.area-text {
  font-weight: normal;
  color: #303133;
}

.date-text {
  font-weight: normal;
  color: #606266;
  font-size: 12px;
}

.jyf-text {
  font-weight: normal;
  color: #303133;
  max-width: 140px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

/* 表格容器样式 */
.table-container {
  flex: 1;
  width: 100%;
  min-height: 0;
  max-width: 100%;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.05);
  padding: 20px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-sizing: border-box;
}

.table-container .base-table-container {
  flex: 1;
  width: 100%;
  min-height: 0;
  max-width: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

/* 表格样式与主题协调 */
:deep(.el-table) {
  width: 100% !important;
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table__header) {
  background: var(--primary-color, #409eff);
}

:deep(.el-table__header th) {
  background: var(--primary-color, #409eff) !important;
  color: white !important;
  font-weight: 600;
  padding: 5px !important;
}

:deep(.el-table__body td) {
  padding: 5px !important;
  border-bottom: 1px solid var(--border-light, #ebeef5);
  font-weight: normal;
  color: #303133;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background: var(--table-stripe-background, #fafafa);
}

:deep(.el-table__body tr:hover) {
  background-color: rgba(64, 158, 255, 0.1);
}

/* 分页器样式 */
.pagination-wrapper {
  padding: 20px;
  background: white;
  display: flex;
  justify-content: center;
  align-items: center;
  border-top: 1px solid #e4e7ed;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  margin-top: 10px;
  border-radius: 0 0 8px 8px;
}

.pagination-wrapper .el-pagination {
  --el-pagination-bg-color: transparent;
  --el-pagination-text-color: #606266;
  --el-pagination-border-radius: 4px;
  --el-pagination-button-color: #606266;
  --el-pagination-button-bg-color: #ffffff;
  --el-pagination-button-disabled-color: #c0c4cc;
  --el-pagination-button-disabled-bg-color: #ffffff;
  --el-pagination-hover-color: #409eff;
  --el-pagination-hover-bg-color: #ecf5ff;
}

.pagination-wrapper .el-pagination .el-pager li {
  border-radius: 4px;
  margin: 0 2px;
  transition: all 0.3s ease;
}

.pagination-wrapper .el-pagination .el-pager li.is-active {
  background-color: #409eff;
  color: white;
  font-weight: 600;
}

.pagination-wrapper .el-pagination .el-pager li:hover {
  background-color: #ecf5ff;
  color: #409eff;
}

.pagination-wrapper .el-pagination .btn-prev,
.pagination-wrapper .el-pagination .btn-next {
  border-radius: 4px;
  margin: 0 4px;
  transition: all 0.3s ease;
}

.pagination-wrapper .el-pagination .btn-prev:hover,
.pagination-wrapper .el-pagination .btn-next:hover {
  background-color: #ecf5ff;
  color: #409eff;
}

.pagination-wrapper .el-pagination .el-pagination__sizes {
  margin-right: 15px;
}

.pagination-wrapper .el-pagination .el-pagination__jump {
  margin-left: 15px;
}

:deep(.el-switch) {
  --el-switch-on-color: var(--primary-color);
}

:deep(.el-tag) {
  border-radius: 4px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input-number) {
  width: 100%;
}

/* 导入说明对话框样式 */
.help-dialog {
  max-height: 80vh;
  overflow-y: auto;
}

.import-help-content {
  line-height: 1.6;
}

.import-help-content h4 {
  color: var(--primary-color);
  margin: 20px 0 10px 0;
  font-size: 16px;
}

.import-help-content h4:first-child {
  margin-top: 0;
}

.format-table table,
.example-table table {
  width: 100%;
  border-collapse: collapse;
  margin: 15px 0;
  font-size: 14px;
}

.format-table th,
.format-table td,
.example-table th,
.example-table td {
  border: 1px solid #e4e7ed;
  padding: 8px 12px;
  text-align: left;
}

.format-table th,
.example-table th {
  background-color: #f5f7fa;
  font-weight: 600;
  color: var(--primary-color);
}

.format-table td:nth-child(3),
.format-table td:nth-child(4) {
  text-align: center;
}

.import-tips ul {
  margin: 10px 0;
  padding-left: 20px;
}

.import-tips li {
  margin: 5px 0;
  color: #606266;
}

.example-table {
  background-color: #fafafa;
  border-radius: 6px;
  padding: 15px;
  margin: 15px 0;
}

.example-table table {
  background-color: white;
  border-radius: 4px;
  overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 1920px) {
  .page-container {
    padding: 15px;
  }
  
  .house-search,
  .house-function-select,
  .house-status-select,
  .house-operator-select {
    gap: 10px;
  }
  
  .house-search .el-input {
    width: 250px !important;
  }
  
  .house-function-select .el-select,
  .house-status-select .el-select {
    width: 120px !important;
  }
  
  .house-operator-select .el-input {
    width: 180px !important;
  }
}

@media (max-width: 1600px) {
  .page-container {
    padding: 10px;
  }
  
  .house-search,
  .house-function-select,
  .house-status-select,
  .house-operator-select {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
  
  .house-search .el-input,
  .house-function-select .el-select,
  .house-status-select .el-select,
  .house-operator-select .el-input {
    width: 100% !important;
  }
}

@media (max-width: 1200px) {
  .action-buttons {
    flex-direction: column;
    gap: 3px;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .table-container {
    padding: 8px;
  }
  
  .pagination-wrapper {
    padding: 10px;
  }
  
  .pagination-wrapper .el-pagination {
    font-size: 12px;
  }
  
  .pagination-wrapper .el-pagination .el-pagination__sizes {
    margin-right: 10px;
  }
  
  .pagination-wrapper .el-pagination .el-pagination__jump {
    margin-left: 10px;
  }
}

@media (max-width: 480px) {
  .pagination-wrapper {
    flex-direction: column;
    gap: 10px;
  }
  
  .pagination-wrapper .el-pagination {
    justify-content: center;
  }
}
</style> 